package com.wjk.cms.util.wx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.wjk.cms.util.ApplicationContextHolder;
import com.wjk.cms.util.CommonUtil;
import com.wjk.cms.util.MD5Util;
import com.wjk.cms.util.pay.WxSslUtil;
import com.wjk.cms.util.wx.wxpay.WXPay;
import com.wjk.cms.util.wx.wxpay.WxPayConfigImpl;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.*;

@Slf4j
public class WxPayUtil {

    private static String mchSerialNo = "4115A02A1E70C425B856181D0BF8B3E983382DD7"; // 商户证书序列号
    // 你的商户私钥
    private static String privateKey = "-----BEGIN PRIVATE KEY-----\n" +
            "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDh/4JrHGkOfFZ4\n" +
            "bJPWI7KJFb77+tuw69+pshHRy44Ssviw9YSOQIPsdtxFD5euxXlGtgqlaY8fObb7\n" +
            "OhjKCi/Di+3KYxCwY8adbgV3BcP9L7uLluKF3bFf1xDnbSOoBuGfHhXEQZD8O8Sr\n" +
            "y3T13bcxT4EYFUACCGg84GZBJHGLZjTcnqjvntVIXFN89v9VaSB6L9bPNit2tYdF\n" +
            "v0p+Q+5x5EeKG6ZLmjX4+sFHSu3EUGklfJ4lInAHJyjOA/YLCND1AwGhMTR/yCBo\n" +
            "TiM2a44aHpwS5/yAV8PkG775U10IvFTF3HAfrIRX40850JpB4SAwnCWkaM7Awx98\n" +
            "bqVmas3LAgMBAAECggEAfpgpDyTn+HRP3786hN6UONQUmoPoIk/Ohvk3oCR9Hh5g\n" +
            "zoeJTEH5ZDEkrA7S8dSuXZzFk+jwghZLWKkvj6VrIge1GQSrKZOKg09JAmYZZi8h\n" +
            "yEyp8UDBBiWr02dAbPQF2KL6oGf19kTooy8iAkPDRXz6nGny4/Cfq1IsFVt7uxBl\n" +
            "G6EhSZKDqeH7xElxF/vPd+KlTfRPx75ABkcMhS0+bGE5zs3W/HoDWcX3U4407I4O\n" +
            "YsvqSUxwwoIZ4K3EMT+dfg8QBoLc0dIU/hNu8wgHhBBz4Ml7ZTu7ChAV9O/203If\n" +
            "qH5oViOuR5EO2zVSW/ela6yrasXBOFi+FAqaFl1o0QKBgQDxu5DzeA2YcBzwrzpU\n" +
            "/NncxRT/6PkfwMjft7wh2zsoG66CqbqsK71NmAl3X2zEMbevCWy7XqFSqv7S+24O\n" +
            "UMPQBeJYM3XgGtGsSwJRsEl2VZwOR6uSZIhRe931asM6F/ZH5UoWZVlmsq1QiYDV\n" +
            "VVpuMJhmAYcoczz4vD0uosdOWQKBgQDvVjP6uMpyGQMMNM1bZ3u8YIYaTpHp6QZz\n" +
            "YE0gefZxy0ZUXFVOGIUbZcCAjzt738yRS6Ab3XLeHmNlquxloctXPS8N53eKAEK+\n" +
            "ZNOBpcWGN+t0dwJIdsqOgSDlffsaWLD/NknAcvAgKwHGdBaTl5jkpUFg9Ju8B/xV\n" +
            "V2nQoWcgwwKBgDRFBYvPysjKfUeB7FASOJ2nM+o+GxhFnGnbld+QQxNiIPL59nZi\n" +
            "ItXTaUCZrrAhvAEqPYuqY6G3fdBrM5n+1sh1bUL7JaLmya3CrmaxgsEGs+7Win/m\n" +
            "Ix/Tc+QsSLiYE9Xp+4IqOhGd0yIWCXiXsy0ebuWnsO0LNgTm1yftZMFJAoGBALto\n" +
            "7u7nAG9zsnU+a4elcrjBhIDZAVz+gXSa9gn2NspIeFvaqVmrzZ70gFaq0dNgHZmw\n" +
            "dEEdmLLhbMfRnaa/mLBJUq06kNpY9eqMnSoqGo/M/eyGvBzuGBKafp31lki9JmvR\n" +
            "oNK3rdwikRNLF9qenLR9ysIXCFOmlSpmdo9Ns6ltAoGAdb57J7f5afwYuOxG4jK0\n" +
            "pouH6C9Oz7VJUat+Gxu1jcX5XmWGEPbhrtccw5VElmWcbKjvTUthpPVqI/KkMa5E\n" +
            "/3wV9xXvpSZWrFXjslBey1L9IcYJ++MonnUn+m9ObFNgtrKtlAXMe6bYXRcC4jvx\n" +
            "nHJ7Zn7UIETiJ+Vorxk6/Ro=\n" +
            "-----END PRIVATE KEY-----";

    // 你的微信支付平台证书
    private static String certificate = "-----BEGIN CERTIFICATE-----\n" +
            "MIID+TCCAuGgAwIBAgIUQRWgKh5wxCW4VhgdC/iz6YM4LdcwDQYJKoZIhvcNAQEL\n" +
            "BQAwXjELMAkGA1UEBhMCQ04xEzARBgNVBAoTClRlbnBheS5jb20xHTAbBgNVBAsT\n" +
            "FFRlbnBheS5jb20gQ0EgQ2VudGVyMRswGQYDVQQDExJUZW5wYXkuY29tIFJvb3Qg\n" +
            "Q0EwHhcNMjAwNDE0MDcyOTQyWhcNMjUwNDEzMDcyOTQyWjCBijETMBEGA1UEAwwK\n" +
            "MTMwNTYwMDEwMTEbMBkGA1UECgwS5b6u5L+h5ZWG5oi357O757ufMTYwNAYDVQQL\n" +
            "DC3lsbHkuJzoiKrml4XpgJrnlLXlrZDnp5HmioDpm4blm6LmnInpmZDlhazlj7gx\n" +
            "CzAJBgNVBAYMAkNOMREwDwYDVQQHDAhTaGVuWmhlbjCCASIwDQYJKoZIhvcNAQEB\n" +
            "BQADggEPADCCAQoCggEBAOH/gmscaQ58Vnhsk9YjsokVvvv627Dr36myEdHLjhKy\n" +
            "+LD1hI5Ag+x23EUPl67FeUa2CqVpjx85tvs6GMoKL8OL7cpjELBjxp1uBXcFw/0v\n" +
            "u4uW4oXdsV/XEOdtI6gG4Z8eFcRBkPw7xKvLdPXdtzFPgRgVQAIIaDzgZkEkcYtm\n" +
            "NNyeqO+e1UhcU3z2/1VpIHov1s82K3a1h0W/Sn5D7nHkR4obpkuaNfj6wUdK7cRQ\n" +
            "aSV8niUicAcnKM4D9gsI0PUDAaExNH/IIGhOIzZrjhoenBLn/IBXw+QbvvlTXQi8\n" +
            "VMXccB+shFfjTznQmkHhIDCcJaRozsDDH3xupWZqzcsCAwEAAaOBgTB/MAkGA1Ud\n" +
            "EwQCMAAwCwYDVR0PBAQDAgTwMGUGA1UdHwReMFwwWqBYoFaGVGh0dHA6Ly9ldmNh\n" +
            "Lml0cnVzLmNvbS5jbi9wdWJsaWMvaXRydXNjcmw/Q0E9MUJENDIyMEU1MERCQzA0\n" +
            "QjA2QUQzOTc1NDk4NDZDMDFDM0U4RUJEMjANBgkqhkiG9w0BAQsFAAOCAQEAKNLG\n" +
            "E+setD/YYdM3tMku1TB85Yjkic8JpCoPZgmpFO52eNDdm2My1nr1n4dYYDQavSIa\n" +
            "oAM5ovY0y0r8SYoSvpU8IZ2xlUXPR+Hv62fg03wp4NW2AdtIwH6aPyCHtDFNBrcJ\n" +
            "yQ+awcyRxnShaBTJmE77bXpCvj2Mcx859ZjgPRCFNHefgFoCaXRFRiLDq4QAQFJk\n" +
            "1l4u/89vGiDsiUDWy5EQQCxIShHd+5qFqJ9Wo7idAwgRTuSNmgrB+irTLJk2UzKm\n" +
            "jZfyvvGjSH0swrKP+l/TRQFqXlML1X8HFV9xaq3jm/XfBnUiQvRHCRTasJqBXzyC\n" +
            "zAprNIADvzBHntcoIQ==\n" +
            "-----END CERTIFICATE-----";


    public static String createPackageSign(SortedMap<String, String> params) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            String k = entry.getKey();
            String v = entry.getValue();
            if (StringUtils.isNotEmpty(v) && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        sb.append("key=" + WxConfig.MCH_KEY());
        return MD5Util.encode(sb.toString(), "UTF-8").toUpperCase();
    }

    public static String createPaySign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();
        for (NameValuePair param : params) {
            sb.append(param.getName() + "=" + param.getValue() + "&");
        }
        sb.append("key=" + WxConfig.MCH_KEY());
        return MD5Util.encode(sb.toString(), "UTF-8");
    }

    /**
     * 微信统一下单
     */
    public static Map<String, String> unifiedOrder(String xml) {
        log.info("微信统一下单 - 请求\n" + xml);
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(WxConfig.UNIFIED_ORDER_URL());
        try {
            httpPost.setEntity(new StringEntity(xml, "UTF-8"));
            HttpResponse response = httpClient.execute(httpPost);
            String responseText = EntityUtils.toString(response.getEntity(), "UTF-8");
            log.info("微信统一下单 - 响应\n" + responseText);
            Map<String, String> map = WxXmlUtil.parseXmlToMap(responseText);
            return map;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return new HashMap<>();
    }

    /**
     * 微信企业付款到零钱
     */
    public static Map<String, String> pay(String xml) {
        WxSslUtil wxSslUtil = ApplicationContextHolder.getBean(WxSslUtil.class);
        log.info("微信企业付款到零钱 - 请求\n" + xml);
        try {
            String responseText = wxSslUtil.doSecuredPost(WxConfig.PAY_URL(), xml);
            log.info("微信企业付款到零钱 - 响应\n" + responseText);
            Map<String, String> map = WxXmlUtil.parseXmlToMap(responseText);
            return map;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return new HashMap<>();
    }

    public static  Map<String, String> queryOrder(String orderCode,String channel) throws Exception {
        String url = "https://api.mch.weixin.qq.com/pay/orderquery";
        String nonce_str = CommonUtil.generateNonceStr();
        SortedMap<String, String> packageParams = new TreeMap<>();
        packageParams.put("appid", WxConfig.GZH_APP_ID());
        packageParams.put("mch_id", WxConfig.MCH_ID());
        packageParams.put("nonce_str", nonce_str);
        packageParams.put("out_trade_no", orderCode);
        WxPayConfigImpl wxPayConfig = new WxPayConfigImpl();
        WXPay wxPay = new WXPay(wxPayConfig);
        Map<String, String> stringStringMap = wxPay.orderQuery(packageParams);
        return  stringStringMap;
    }


    /**
     * 微信退款
     */
    public static Map<String, String> refund(String xml) {
        WxSslUtil wxSslUtil = ApplicationContextHolder.getBean(WxSslUtil.class);
        log.info("微信退款 - 请求\n" + xml);
        try {
            String refundUrl = "https://api.mch.weixin.qq.com/secapi/pay/refund";
            String responseText = wxSslUtil.doSecuredPost(refundUrl, xml);
            log.info("微信退款 - 响应\n" + responseText);
            Map<String, String> map = WxXmlUtil.parseXmlToMap(responseText);
            return map;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return new HashMap<>();
    }



    public static void main(String[] args) throws Exception {

    }

}
